<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false" draggable
    :width="modalWidth" @before-ok="handleSubmit" @close="handleReset">
    <a-form ref="formRef" :model="formState" :layout="formLayout" :size="formSize" @submit-success="handleSubmit">
      <!-- 新增：项目任务选择卡片 -->
      <a-card title="关联试验任务" :bordered="false" class="project-task-card" :body-style="{ padding: '16px 0' }">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="选择项目" field="projectId" >
              <a-select v-model="selectedProject" :options="projectOptions" placeholder="请选择项目" allow-clear
                @change="handleProjectChange" :loading="projectLoading">
                <template #suffix>
                  <icon-search />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="选择任务" field="taskId" >
              <a-select v-model="selectedTask" :options="taskOptions" placeholder="请先选择项目" allow-clear
                :disabled="!selectedProject" :loading="taskLoading">
                <template #suffix>
                  <icon-search />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <!-- 原有出库表单 -->
      <a-divider orientation="left">出库信息</a-divider>

      <!-- 库存信息提示卡片 -->
      <a-alert v-if="currentRecord" type="info" :bordered="true" class="inventory-alert">
        <template #title>
          <div class="inventory-info">
            <span class="device-name">设备名称：{{ currentRecord.deviceName }}</span>
            <span class="inventory-count">当前库存：<strong>{{ currentRecord.count || 0 }}</strong></span>
            <span class="max-delivery">最多可出库：<strong>{{ currentRecord.count || 0 }}</strong></span>
          </div>
        </template>
      </a-alert>

      <a-row :gutter="gridGutter">
        <a-col :span="12">
          <a-form-item 
            label="出库数量" 
            field="deliveryCount" 
            :rules="deliveryCountRules" 
            label-col-flex="80px"
            :help="currentRecord ? `当前库存：${currentRecord.count || 0}，请输入 1-${currentRecord.count || 0} 之间的数量` : ''"
          >
            <a-input-number 
              v-model="formState.deliveryCount" 
              :min="1" 
              :max="currentRecord?.count ? Number(currentRecord.count) : 100000" 
              :placeholder="`请输入出库数量（最多${currentRecord?.count || 0}）`"
              style="width: 100%" 
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="出库时间" field="deliveryDate" :rules="requiredRule">
            <a-date-picker v-model="formState.deliveryDate" show-time format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="物资去向" field="destination" :rules="requiredRule">
            <a-select v-model="formState.destination" :options="destinationOptions" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="使用人" field="createUser" :rules="requiredRule">
            <a-select v-model="formState.createUser" :options="userOptions" :loading="userLoading"
              :field-names="{ value: 'id', label: 'nickname' }" @search="handleUserSearch" allow-clear
              style="width: 100%" />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="备注" field="remark" :rules="remarkRules">
            <a-textarea v-model="formState.remark" placeholder="请输入备注信息" :auto-size="{ minRows: 3, maxRows: 5 }" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useWindowSize } from '@vueuse/core'
import dayjs from 'dayjs'
import { Message } from '@arco-design/web-vue'
import {
  deliveryDevice,
  type DeviceStoreResp,
  type DeliveryRequest
} from '@/apis/generator/deviceStore'
import {
  searchUsers,
  type UserOption
} from '@/apis/generator/deviceCirculation'
import {
  listProjectStats,
  listTaskStats
} from '@/apis/task/taskSituationChart'

const emit = defineEmits(['delivery-success'])

// UI Configuration
const { width } = useWindowSize()
const modalWidth = computed(() => width.value >= 800 ? '800px' : '100%')
const formLayout = 'vertical'
const formSize = 'large'
const gridGutter = 16

// Component State
const visible = ref(false)
const formRef = ref()
const currentRecord = ref<DeviceStoreResp>()
const userLoading = ref(false)
const userOptions = ref<UserOption[]>([])

const selectedProject = ref<number | null>(null)
const selectedTask = ref<number | null>(null)
const projectOptions = ref<{ value: number, label: string }[]>([])
const taskOptions = ref<{ value: number, label: string }[]>([])
const projectLoading = ref(false)
const taskLoading = ref(false)
// Form Configuration
const requiredRule = { required: true, message: '必填项' }
// 动态生成出库数量验证规则
const deliveryCountRules = computed(() => {
  const maxCount = currentRecord.value?.count ? Number(currentRecord.value.count) : 100000
  return [
    requiredRule,
    { 
      type: 'number', 
      min: 1, 
      max: maxCount, 
      message: `数量范围1-${maxCount}` 
    }
  ]
})

// 监听库存变化，自动调整出库数量
watch(() => currentRecord.value?.count, (newCount) => {
  if (newCount && formState.value.deliveryCount > Number(newCount)) {
    formState.value.deliveryCount = Number(newCount)
  }
}, { immediate: true })
const remarkRules = [{ max: 200, message: '最长200个字符' }]

const destinationOptions = [
  { value: 0, label: '周转库' },
  { value: 1, label: '外借' },
  { value: 2, label: '其他'}
]

// Form State
const formState = ref({
  deliveryCount: 1,
  deliveryDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  destination: 1,
  createUser: undefined as string | undefined,
  remark: ''
})

// Computed
const title = computed(() => `设备出库 - ${currentRecord.value?.deviceName || ''}`)

// Methods


// 获取项目列表
const fetchProjects = async () => {
  projectLoading.value = true
  try {
    const res = await listProjectStats()
    if (res.success && res.data) {
      const dataList = Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data) ? res.data : [])
      projectOptions.value = dataList.map((item: any) => ({
        value: item.id,
        label: `${item.name} (${item.taskCount}个任务)`
      }))
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    Message.error('获取项目列表失败')
  } finally {
    projectLoading.value = false
  }
}

// 项目变更时获取任务列表
const handleProjectChange = async (projectId: number) => {
  selectedTask.value = null
  taskOptions.value = []
  taskLoading.value = true

  try {
    const res = await listTaskStats(projectId)
    if (res.success && res.data) {
      const dataList = Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data) ? res.data : [])
      taskOptions.value = dataList.map((item: any) => ({
        value: item.id,
        label: `${item.name} (总试验次数: ${item.taskTestLogTotal}h)`
      }))
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    Message.error('获取任务列表失败')
  } finally {
    taskLoading.value = false
  }
}

const handleUserSearch = async () => {
  try {
    userLoading.value = true
    const users = await searchUsers()
    userOptions.value = users.map(user => ({
      id: user.id,
      nickname: user.nickname || '未知用户'
    }))
  } catch (error) {
    Message.error('搜索用户失败')
  } finally {
    userLoading.value = false
  }
}

// 重置时也清空项目任务选择
const handleReset = () => {
  formState.value = {
    deliveryCount: 1,
    deliveryDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    destination: 1,
    createUser: undefined,
    remark: ''
  }
  selectedProject.value = null
  selectedTask.value = null
  userOptions.value = []
  currentRecord.value = undefined
  nextTick(() => formRef.value?.resetFields())
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()

    if (!currentRecord.value?.id) {
      Message.error('未获取到设备ID')
      return false
    }



    const submitData: DeliveryRequest = {
      id: currentRecord.value.id,
      deliveryCount: formState.value.deliveryCount,
      location: currentRecord.value.location || '',
      deliveryDate: dayjs(formState.value.deliveryDate).format('YYYY-MM-DD HH:mm:ss'),
      destination: formState.value.destination,
      createUser: formState.value.createUser?.toString() || '',
      remark: formState.value.remark?.trim() || '',
      taskId: selectedTask.value || null, // 添加任务ID
      backTime: '', // 已删除字段，传空字符串
      scarpTime: '' // 已删除字段，传空字符串
    }

    const { success, msg } = await deliveryDevice(submitData)

    if (!success) {
      Message.error(msg || '出库失败')
      return false
    }

    Message.success('出库成功')
    emit('delivery-success')
    return true
  } catch (error: any) {
    Message.error(error.message || '提交失败')
    return false
  }
}

const open = (record: DeviceStoreResp) => {
  currentRecord.value = record
  formState.value = {
    deliveryCount: 1,
    deliveryDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    destination: 1,
    createUser: undefined,
    remark: ''
  }
  selectedProject.value = null
  selectedTask.value = null
  fetchProjects() // 加载项目列表
  handleUserSearch()
  visible.value = true
}

defineExpose({ open })
</script>

<style scoped>
:deep(.ant-form-item-label) {
  font-weight: bold;
  margin-bottom: 4px;
}

:deep(.ant-form-item-control-input-content) {
  margin-bottom: 12px;
}

.project-task-card {
  margin-bottom: 16px;
  border-radius: 4px;
  background: var(--color-fill-2);
  border: 1px solid var(--color-border-2);
}

.project-task-card :deep(.arco-card-header) {
  border-bottom: 1px solid var(--color-border-2);
  padding: 12px 16px;
  font-weight: 500;
}

/* 调整表单标签对齐 */
:deep(.arco-form-item-label) {
  justify-content: flex-start;
}

/* 调整选择器样式 */
:deep(.arco-select-view) {
  border-radius: 4px;
}

/* 库存信息提示样式 */
.inventory-alert {
  margin-bottom: 16px;
}

.inventory-info {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.device-name {
  font-weight: 500;
  color: var(--color-text-1);
}

.inventory-count,
.max-delivery {
  color: var(--color-text-2);
}

.inventory-count strong,
.max-delivery strong {
  color: var(--color-primary);
  font-size: 16px;
  font-weight: 600;
}
</style>